import Vue from 'vue'
import Router from 'vue-router'
import config from './config/index'
import store from './store/index.js';
Vue.use(Router);

var route = new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [{
        path: '/',
        name: 'index',
        meta: {
            requireLogin: true // 当前路由需要校验
        },
        component: resolve => require(['@/views/index.vue'], resolve),
    }, {
        path: '/login',
        name: 'login',
        component: resolve => require(['@/views/pub/login.vue'], resolve),
    }],
    //设置初始化页面滚动位置
    scrollBehavior(to, from, savedPosition) {
        // console.log('savedPosition:', savedPosition)
        if (to.meta.keepAlive) {
            return savedPosition
        } else {
            return { x: 0, y: 0 }
        }
    }
});

//全局路由前置守卫
route.beforeEach((to, from, next) => {
    document.title = to.meta.title ? to.meta.title : config.title; //设置标题
    if (to.meta.requireLogin) {
        if (store.state.user.loginState == "" || store.state.user.loginState == "200") {
            next({ path: '/login' })
        } else {
            next();
        }
    } else {
        next();
    }
});

//全局路由后置守卫
route.afterEach((to, from) => {
    // console.log(to, from)
})

export default route;